# == Schema Information
#
# Table name: wallet_logs
#
#  id                 :integer          not null, primary key
#  transfer           :integer          not null
#  state              :integer          not null
#  trade_type         :string
#  charge_id          :string
#  amount             :float
#  total              :float
#  strategy_result_id :integer
#  user_id            :integer          not null
#  created_at         :datetime         not null
#  updated_at         :datetime         not null
#  account_number     :string
#  account_bank       :string
#  account_branch     :string
#  account_name       :string
#  paid               :boolean          default(FALSE)
#

class WalletLog < ActiveRecord::Base

  include Pingppable

	belongs_to :user
  belongs_to :strategy_result

	STATE = {
    -1 => 'invalid',
    0  => 'prehead',
    1  => 'completed'
  }
  TRANSFER = {
    0  => '存进',       # 存进
    1  => '支出',       # 支出
    2  => '收入',       # 收入
    3  => '提现',       # 提现
  }

  validates :trade_type, inclusion: {in: [nil, 'alipay', 'alipay_pc_direct', 'local', 'wx_pub'], message: '不在所选范围之内'} 

  validates_numericality_of :amount, greater_than_or_equal_to: 0.01, message: "流水金额大于0.01"
  validates_numericality_of :total, greater_than_or_equal_to: 0, message: "帐户总额必须大于等于0"

  scope :withdraw, -> {where(state: 1, transfer: 3).order(updated_at: :desc)}

  # default_scope { where(state: 1, transfer: 3, paid: false) }

  def show_hash
    {
      id: id,
      time: created_at.to_i,
      transfer: TRANSFER[transfer],
      amount: amount,
      info: extra_info 
    }
  end

  def extra_info
    case transfer
    when 2
      "来自订单 #{strategy_result.try(:order).try(:serial_number)}"
    when 3
      [account_bank, account_number].join(' ')
    else
      ''
    end
  end
#introducer_rebate_amount


  # 支付/充值
  def generate_pay(remote_ip="127.0.0.1")
    charge = self.pingpp_charge(payment_options(remote_ip))
    charge
  end

  # 提现
  def generate_withdraw
    transfer = self.pingpp_transfer(withdraw_options)
    transfer
  end

  def p_hash
    {
      order_no: "wallet#{id}",
      channel:  trade_type,
      amount:   amount * 100,
      currency: "cny",
      
    }
  end

  def payment_options(remote_ip="127.0.0.1")
    p_hash.merge(
      subject:   '支付/充值',
      body:      "充值： #{amount}",
      client_ip: remote_ip,
      extra:    extra_hash
    )
  end

  def extra_hash
    case trade_type
    when 'wx_pub'
      {open_id: user.open_id}
    when 'alipay_pc_direct'
      {success_url: "https://www.salesgj.com/#/app/pay?current=2"}
    end
  end

  def withdraw_options
    p_hash.merge(
      type:        "b2c",
      recipient:   user.mobile,
      description: "提现",
      extra:  _extra_hash   
    )
  end

  def _extra_hash
    {
      recipient_name: user.name
    }
  end

end
